// FreeZzaphConfiguration.cs
// 
// Copyright © 2009 FreeZzaph
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System;
using System.Collections.Generic;
using System.Configuration;

namespace FreeZzaphCLI
{
	
	internal class FreeZzaphConfiguration
	{
		private Configuration exeConfig;
		private Configuration localConfig;
		
		private static FreeZzaphConfiguration instance;
		public static FreeZzaphConfiguration Instance
		{
			get
			{
				if (instance == null)
					instance = new FreeZzaphConfiguration();
				return instance;
			}
		}
		private FreeZzaphConfiguration()
		{
			exeConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
			localConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
		}
		
		public string this[string key]
		{
			get
			{
				if (localConfig.AppSettings.Settings[key] != null)
					return localConfig.AppSettings.Settings[key].Value;
				
				if (exeConfig.AppSettings.Settings[key] != null)
					return exeConfig.AppSettings.Settings[key].Value;
				
				return null;
			}
			set
			{
				if (exeConfig.AppSettings.Settings[key] != null)
				{
					if (localConfig.AppSettings.Settings[key] == null)
						localConfig.AppSettings.Settings.Add(key, value);
					else
						 localConfig.AppSettings.Settings[key].Value = value;
					localConfig.Save();
				}
			}
		}
		
		public IList<string> Keys
		{
			get
			{
				List<string> keyList = new List<string>();
				
				foreach (string key in localConfig.AppSettings.Settings.AllKeys)
				{
					if (!keyList.Contains(key))
						keyList.Add(key);
				}
				foreach (string key in exeConfig.AppSettings.Settings.AllKeys)
				{
					if (!keyList.Contains(key))
						keyList.Add(key);
				}
				
				return keyList;
			}
		}
		
		public void Reset(string key)
		{
			if (localConfig.AppSettings.Settings[key] != null)
			{
				localConfig.AppSettings.Settings.Remove(key);
				localConfig.Save();
			}
		}
	}
}
